<?php
class UserAction extends Action {
	//用户列表
    public function index(){
    	$this->getMuen();
		
		$User = M('User');
		$UserList = $User->select();
		
		$this->assign('userlist', $UserList);
		
    	$this->display();
    }
    
    //添加用户
    public function add(){
    	$this->getMuen();
		
    	$this->display();
    }
    
    //添加用户表单提交
    public function addAction(){
	    $this->getMuen();
	    
	    $UserName = $this->_post('username');
	    $PassWord = $this->_post('password');
	    $EnPassWord = $this->_post('enpassword');
	    
	    if(empty($UserName) || empty($PassWord) || empty($EnPassWord)){
			$this->error("用户或密码不能为空");
			return;
	    }
	    
	    if($EnPassWord !== $PassWord){
		    $this->error("密码与确认密码不相同");
		    return;
	    }
	    
    	$User = M('User');
		$isUser = $User->where("`username` = '$UserName'")->find();
		
		if($isUser){
			$this->error("用户已存在");
			return;
		}else{
			
			$data = array(
				'username' => $UserName,
				'password' => md5($PassWord),
				'ctime' => time(),
				'utime' => time(),
			);
			
			if($User->add($data)){
				 $this->success('用户添加成功', '__URL__/index');
			}else{
				$this->error("用户添加失败");
			}
		}
    }
    
    public function delete(){
    	$this->getMuen();
    	
    	$Uid = $this->_get('id');
    	
    	$User = M('User');
    	
    	if($Uid == 1){
	    	$this->error('超级用户不可删除', '__URL__/index');
    	}
	    if($User->where('id='.$Uid)->delete()){
			$this->success('删除用户成功', '__URL__/index');
		}
    }
    
    public function edit(){
    	$this->getMuen();
    
    	$Uid = $this->_get('id');
    	
    	$User = M('User');
    	
    	$UserData = $User->where('id = '.$Uid)->find();
    	
    	$this->assign('user', $UserData);
    	
    	$this->display();
    	
    }
    
    public function editAction(){
    	$this->getMuen();
    	
    	$Uid = $this->_get('id');
    	$PassWord = $this->_post('password');
    	$newP = $this->_post('newp');
    	$newPa = $this->_post('newpa');
    	
    	
    	if(empty($PassWord) || empty($newP) || empty($newPa)){
	    	$this->error('密码不能为空');
    	}else if($newP != $newPa){
	    	$this->error('新密码两次输入不一致');
    	}
    	    	
    	$User = M('User');
    	
    	$UserData = $User->where('id = '.$Uid)->find();
    	
    	if($UserData['password'] !== md5($PassWord)){
	    	$this->error('密码错误');
    	}else if($UserData['password'] == md5($newPa)){
	    	$this->error('新密码与旧密码不能相同');
    	}else{
    		$data['password'] = md5($newPa);
	    	if($User->where('id = '.$Uid)->save($data)){
		    	$this->success('修改用户数据成功', '__URL__/index');
	    	}else{
		    	$this->error('修改用户数据失败');
	    	}
    	}
    }
    
    public function getMuen(){
    	R("Login/isLogin");
    	
	   	$menu = include(COMMON_PATH.'menu.php');
		$this->assign('menu', $menu);
    }
}